package logic

import (
	"context"
	"encoding/json"
	"strconv"

	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
)

type QuestionDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	modelQ model.QuestionModel
	modelO model.OptionModel
	rds    *redis.Redis
}

var QuestionDetailPrefix = "question:detail:id:"

func NewQuestionDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuestionDetailLogic {
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: svcCtx.Config.Redis.Host,
		Pass: svcCtx.Config.Redis.Pass,
		Type: svcCtx.Config.Redis.Type,
	})
	if err != nil {
		logx.Errorf("redis init error: %v", err)
	}
	return &QuestionDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		modelQ: model.NewQuestionModel(svcCtx.Orm),
		modelO: model.NewOptionModel(svcCtx.Orm),
		rds:    rds,
	}
}

func (l *QuestionDetailLogic) QuestionDetail(req *types.IdRequest) (resp *types.QuestionDetailResponse, err error) {
	// todo: add your logic here and delete this line
	data, err := l.rds.GetCtx(l.ctx, ServeyDetailPrefix+strconv.FormatInt(req.Id, 10))
	if len(data) > 0 {
		var questionInfo *types.QuestionItemResponse
		err = json.Unmarshal([]byte(data), &questionInfo)
		if err != nil {
			return nil, err
		}
		l.rds.ExpireCtx(l.ctx, ServeyDetailPrefix+strconv.FormatInt(req.Id, 10), 3600*2)
		return &types.QuestionDetailResponse{
			Code: 200,
			Msg:  "search success",
			Data: *questionInfo,
		}, nil
	}
	// 查询下属的所有问题
	question, err := l.modelQ.FindOne(l.ctx, nil, req.Id)
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}
	options, err := l.modelO.FindListByQid(l.ctx, nil, req.Id)
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}
	questionResp := &types.QuestionItemResponse{
		ServeyId:     question.ServeyId,
		QstContent:   question.QstContent,
		Id:           question.Id,
		Type:         question.Type,
		QstSort:      question.QstSort,
		IsMustAnswer: question.IsMustAnswer,
		IsShow:       question.IsShow,
	}
	for i := 0; i < len(options); i++ {
		questionResp.Options = append(questionResp.Options, &types.OptionalItemResponse{
			QuestionId: options[i].QuestionId,
			OpContent:  options[i].OpContent,
			IsTrue:     options[i].IsTrue,
			Id:         options[i].Id,
		})
	}
	byteData, err := json.Marshal(questionResp)
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}
	_, err = l.rds.SetnxExCtx(l.ctx, QuestionDetailPrefix+strconv.FormatInt(req.Id, 10), string(byteData), 3600*2)
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}
	return &types.QuestionDetailResponse{
		Code: 200,
		Msg:  "查询成功",
		Data: *questionResp,
	}, nil
}
